package backtracking;

import java.util.ArrayList;
import java.util.List;
public class GenerateParentheses22 {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        backtrace( n, n, result, new StringBuffer());
        return result;
    }

    public void backtrace( int left, int right, List<String> result, StringBuffer cur) {
        if(left<0){
            return;
        }
        if(right<0){
            return;
        }

        if (left > right) {
            return;
        }
        if (left == 0 && right == 0) {
            result.add(cur.toString());
            return;
        }
        cur.append('(');
        backtrace(--left, right, result, cur);
        cur.deleteCharAt(cur.length()-1);
        left++;
        cur.append(')');
        backtrace(left, --right, result, cur);
        cur.deleteCharAt(cur.length()-1);
        right++;
    }
}
